/*
 This file will contain all the functions that have
 to do with interacting with the FTP server
 */

#include "cli_net.h"
#define RC_SIZE 512

/*
 This function will transfer the given file to the server
 @param hostname: the hostname of the server
 @param port: the port the server is listening on
 @param file: the file to transfer
 */
void transferFile(char *hostname, char *port)
{
    //connect to the server
    int sockfd = connectToServer(hostname, port);
    
    char reply[RC_SIZE];
    
    
    
    //write the file name to the server 
    if(read(sockfd, reply, RC_SIZE) < 0)
    {
        perror("Error reading from server");
        exit(1);
    }
    
    printf("%s", reply);
    
    
    close(sockfd);
}

/*
 This function will connect to the server
 @param hostname: hostname of the server
 @param port: port the server is listening on
 @return: file descriptor of the socket
 */
int connectToServer(char *hostname, char *port)
{
    struct addrinfo hints, *res, *res0;
    int sockfd = -1;
    
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    
    if (getaddrinfo(hostname, port, &hints, &res0)) {
        perror("Error resolving hostname");
        exit(1);
    }
    for (res = res0; res; res = res->ai_next) {
        
        sockfd = socket(res->ai_family, res->ai_socktype,
                        res->ai_protocol);
        if (sockfd < 0) {
            continue;
        }
        
        if (connect(sockfd, res->ai_addr, res->ai_addrlen) < 0) {
            close(sockfd);
            sockfd = -1;
            continue;
        }
        
        break;  /* okay we got one */
    }
    if (sockfd < 0) {
        perror("Failed to connect");
        /*NOTREACHED*/
    }
    freeaddrinfo(res0);
    return sockfd;
    
}
